package main

import (
	"database/sql"
	"fmt"
	"math"
	"net/http"
	"os"
	"regexp"
	"strconv"
	"strings"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/joho/godotenv"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

// Column 描述表的列定义
type Column struct {
	Name       string           `json:"name"`
	Type       string           `json:"type"`                          // 支持多种MySQL数据类型
	Attributes ColumnAttributes `json:"attributes,omitempty" gorm:"-"` // 使用gorm:"-"标签使其在数据库操作时被忽略
	Comment    string           `json:"comment,omitempty"`             // 列的注释
}

// ColumnAttributes 描述列的属性
type ColumnAttributes struct {
	NotNull       bool   `json:"notNull"`
	DefaultValue  string `json:"defaultValue"`
	Unique        bool   `json:"unique"`
	Length        string `json:"length"`
	Scale         string `json:"scale"`
	Unsigned      bool   `json:"unsigned"`
	AutoIncrement bool   `json:"autoIncrement"`
	PrimaryKey    bool   `json:"primaryKey"`
}

// ColumnDescription 存储列的注释
type ColumnDescription struct {
	ID           uint   `gorm:"primaryKey" json:"id"`
	DatabaseName string `json:"database_name"`
	TableName    string `json:"table_name"`
	ColumnName   string `json:"column_name"`
	Comment      string `gorm:"column:comment" json:"comment"` // 确保字段映射到数据库的comment列
}

// DynamicTable 用于存储表数据的通用结构
type DynamicTable struct {
	ID     uint                   `gorm:"primaryKey" json:"id"`
	Fields map[string]interface{} `gorm:"-" json:"fields"` // 动态字段
}

// 全局数据库连接
var db *gorm.DB

// 数据库连接配置
type DBConfig struct {
	Host     string `json:"host"`
	Port     string `json:"port"`
	User     string `json:"user"`
	Password string `json:"password"`
	DBName   string `json:"dbname"`
}

// 默认数据库配置
var dbConfig = DBConfig{
	Host:     "127.0.0.1",
	Port:     "3306",
	User:     "dynamic_user",
	Password: "dynamic_password",
	DBName:   "dynamic_db",
}

func main() {
	// 加载.env文件
	loadEnvConfig()

	// 初始化数据库
	connectDB()

	// 初始化路由
	r := gin.Default()

	// 添加CORS中间件，允许跨域访问
	r.Use(func(c *gin.Context) {
		c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
		c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
		c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
		c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT, DELETE")

		if c.Request.Method == "OPTIONS" {
			c.AbortWithStatus(204)
			return
		}

		c.Next()
	})

	// 提供静态文件（前端页面）
	r.Static("/static", "./static")
	r.GET("/", func(c *gin.Context) {
		c.File("./static/index.html")
	})

	// API 端点
	// 获取数据库连接配置
	r.GET("/api/dbconfig", getDBConfig)
	// 更新数据库连接配置
	r.POST("/api/dbconfig", updateDBConfig)
	// 获取所有数据库
	r.GET("/api/databases", getDatabases)
	// 获取所有表
	r.GET("/api/tables", getTables)
	// 创建新表
	r.POST("/api/tables", createTable)
	// 查询映射表
	r.GET("/api/map/search", searchMapTable)
	// 获取表结构
	r.GET("/api/table/:table", getTableStructure)
	// 添加新列
	r.POST("/api/table/:table", updateTableStructure)
	// 删除列
	r.DELETE("/api/table/:table/column/:column", deleteColumn)
	// 重命名列
	r.PUT("/api/table/:table/column/:column", renameColumn)
	// 修改列属性
	r.PATCH("/api/table/:table/column/:column", updateColumnAttributes)
	// 获取数据
	r.GET("/api/data/:table", getData)
	// 添加数据
	r.POST("/api/data/:table", createData)
	// 更新数据
	r.PUT("/api/data/:table/:id", updateData)
	// 删除数据
	r.DELETE("/api/data/:table/:id", deleteData)

	// 启动服务
	r.Run(":8080")
}

// 从.env文件加载配置
func loadEnvConfig() {
	// 尝试加载.env文件
	if err := godotenv.Load(); err != nil {
		fmt.Printf("警告: 未找到.env文件或无法加载: %v\n", err)
		// 继续使用默认配置
	} else {
		// 从环境变量读取配置
		if host := os.Getenv("DB_HOST"); host != "" {
			dbConfig.Host = host
		}
		if port := os.Getenv("DB_PORT"); port != "" {
			dbConfig.Port = port
		}
		if user := os.Getenv("DB_USER"); user != "" {
			dbConfig.User = user
		}
		if password := os.Getenv("DB_PASSWORD"); password != "" {
			dbConfig.Password = password
		}
		if dbName := os.Getenv("DB_NAME"); dbName != "" {
			dbConfig.DBName = dbName
		}

		fmt.Println("已从.env文件加载数据库配置")
	}
}

// 连接数据库
func connectDB() {
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		dbConfig.User, dbConfig.Password, dbConfig.Host, dbConfig.Port, dbConfig.DBName)

	var err error
	db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		fmt.Printf("数据库连接失败: %v\n", err)
		// 不要立即退出，让服务继续运行，用户可以通过UI修改连接信息
		return
	}

	// 测试连接
	sqlDB, err := db.DB()
	if err != nil {
		fmt.Printf("获取数据库连接失败: %v\n", err)
		db = nil // 重置数据库连接
		return
	}

	// 设置连接池参数
	sqlDB.SetMaxIdleConns(10)
	sqlDB.SetMaxOpenConns(100)
	sqlDB.SetConnMaxLifetime(time.Hour)

	// 测试连接
	if err := sqlDB.Ping(); err != nil {
		fmt.Printf("数据库连接测试失败: %v\n", err)
		db = nil // 重置数据库连接
		return
	}

	fmt.Println("数据库连接成功")

	// 自动迁移表结构
	if err := db.AutoMigrate(&DynamicTable{}, &ColumnDescription{}); err != nil {
		fmt.Printf("表结构迁移失败: %v\n", err)
	}

	// 检查并修复ColumnDescription表结构
	ensureColumnDescriptionTable()
}

// 确保ColumnDescription表结构正确
func ensureColumnDescriptionTable() {
	if db == nil {
		fmt.Println("数据库未连接，无法检查ColumnDescription表结构")
		return
	}

	// 检查comment列是否存在
	var hasCommentColumn bool
	err := db.Raw("SELECT COUNT(*) > 0 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'column_descriptions' AND COLUMN_NAME = 'comment'").Scan(&hasCommentColumn).Error
	if err != nil {
		fmt.Printf("检查ColumnDescription表结构失败: %v\n", err)
		return
	}

	// 如果comment列不存在，尝试添加
	if !hasCommentColumn {
		fmt.Println("ColumnDescription表缺少comment列，尝试添加...")

		// 检查是否存在description列（可能是旧版本的列名）
		var hasDescriptionColumn bool
		err := db.Raw("SELECT COUNT(*) > 0 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'column_descriptions' AND COLUMN_NAME = 'description'").Scan(&hasDescriptionColumn).Error
		if err != nil {
			fmt.Printf("检查description列失败: %v\n", err)
			return
		}

		if hasDescriptionColumn {
			// 如果存在description列，重命名为comment
			fmt.Println("找到description列，重命名为comment...")
			err = db.Exec("ALTER TABLE column_descriptions CHANGE COLUMN description comment TEXT").Error
			if err != nil {
				fmt.Printf("重命名列失败: %v\n", err)
				return
			}
			fmt.Println("成功将description列重命名为comment")
		} else {
			// 如果不存在description列，直接添加comment列
			fmt.Println("添加comment列...")
			err = db.Exec("ALTER TABLE column_descriptions ADD COLUMN comment TEXT").Error
			if err != nil {
				fmt.Printf("添加comment列失败: %v\n", err)
				return
			}
			fmt.Println("成功添加comment列")
		}
	}
}

// 获取数据库连接配置
func getDBConfig(c *gin.Context) {
	// 返回当前配置，但隐藏密码
	configToReturn := dbConfig
	configToReturn.Password = "" // 出于安全考虑，不返回密码
	c.JSON(http.StatusOK, configToReturn)
}

// 更新数据库连接配置
func updateDBConfig(c *gin.Context) {
	var newConfig DBConfig
	if err := c.ShouldBindJSON(&newConfig); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的配置数据"})
		return
	}

	// 验证必填字段
	if newConfig.Host == "" || newConfig.Port == "" || newConfig.User == "" || newConfig.DBName == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "主机、端口、用户名和数据库名为必填项"})
		return
	}

	// 如果密码为空，保留原密码
	if newConfig.Password == "" {
		newConfig.Password = dbConfig.Password
	}

	// 保存新配置
	oldConfig := dbConfig
	dbConfig = newConfig

	// 重新连接数据库
	connectDB()

	// 检查连接是否成功
	if db == nil {
		// 连接失败，恢复旧配置
		dbConfig = oldConfig
		c.JSON(http.StatusInternalServerError, gin.H{"error": "数据库连接失败"})
		return
	}

	// 测试连接
	var result int
	if err := db.Raw("SELECT 1").Scan(&result).Error; err != nil {
		// 连接测试失败，恢复旧配置
		dbConfig = oldConfig
		connectDB() // 尝试恢复旧连接
		c.JSON(http.StatusInternalServerError, gin.H{"error": "数据库连接测试失败: " + err.Error()})
		return
	}

	// 连接成功，保存配置到.env文件
	saveConfigToEnv()

	c.JSON(http.StatusOK, gin.H{"message": "数据库连接配置已更新"})
}

// 保存配置到.env文件
func saveConfigToEnv() {
	// 准备.env文件内容
	envContent := fmt.Sprintf(`DB_HOST=%s
DB_PORT=%s
DB_USER=%s
DB_PASSWORD=%s
DB_NAME=%s
`, dbConfig.Host, dbConfig.Port, dbConfig.User, dbConfig.Password, dbConfig.DBName)

	// 写入.env文件
	if err := os.WriteFile(".env", []byte(envContent), 0644); err != nil {
		fmt.Printf("警告: 无法保存配置到.env文件: %v\n", err)
	} else {
		fmt.Println("配置已保存到.env文件")
	}
}

// 检查数据库连接
func checkDBConnection(c *gin.Context) bool {
	if db == nil {
		c.JSON(http.StatusServiceUnavailable, gin.H{"error": "数据库未连接，请检查连接配置"})
		return false
	}

	// 使用更安全的方式测试连接
	sqlDB, err := db.DB()
	if err != nil {
		c.JSON(http.StatusServiceUnavailable, gin.H{"error": "获取数据库连接失败: " + err.Error()})
		return false
	}

	// 使用Ping而不是执行SQL查询
	if err := sqlDB.Ping(); err != nil {
		c.JSON(http.StatusServiceUnavailable, gin.H{"error": "数据库连接失败: " + err.Error()})
		return false
	}

	return true
}

// 获取所有数据库
func getDatabases(c *gin.Context) {
	if !checkDBConnection(c) {
		return
	}

	var databases []string
	// 使用更明确的查询，排除系统数据库
	query := `
		SELECT SCHEMA_NAME 
		FROM INFORMATION_SCHEMA.SCHEMATA 
		WHERE SCHEMA_NAME NOT IN ('information_schema', 'mysql', 'performance_schema', 'sys')
		ORDER BY SCHEMA_NAME
	`

	// 使用更安全的方式执行查询
	rows, err := db.Raw(query).Rows()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "获取数据库列表失败: " + err.Error()})
		return
	}
	defer rows.Close()

	for rows.Next() {
		var dbName string
		if err := rows.Scan(&dbName); err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": "读取数据库名失败: " + err.Error()})
			return
		}
		databases = append(databases, dbName)
	}

	// 如果没有找到任何数据库，尝试使用简单查询
	if len(databases) == 0 {
		rows, err := db.Raw("SHOW DATABASES").Rows()
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": "获取数据库列表失败: " + err.Error()})
			return
		}
		defer rows.Close()

		for rows.Next() {
			var dbName string
			if err := rows.Scan(&dbName); err != nil {
				c.JSON(http.StatusInternalServerError, gin.H{"error": "读取数据库名失败: " + err.Error()})
				return
			}
			// 过滤系统数据库
			if dbName != "information_schema" && dbName != "mysql" &&
				dbName != "performance_schema" && dbName != "sys" {
				databases = append(databases, dbName)
			}
		}
	}

	c.JSON(http.StatusOK, databases)
}

// 获取所有表
func getTables(c *gin.Context) {
	if !checkDBConnection(c) {
		return
	}

	// 获取查询参数中的数据库名，如果没有则使用当前连接的数据库
	dbName := c.DefaultQuery("database", "")

	var query string
	if dbName != "" {
		// 如果指定了数据库，则查询该数据库中的表
		query = fmt.Sprintf("SHOW TABLES FROM %s", dbName)
	} else {
		// 否则查询当前数据库的表
		query = "SHOW TABLES"
	}

	var tables []string
	if err := db.Raw(query).Scan(&tables).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	c.JSON(http.StatusOK, tables)
}

// 获取表结构（列定义）
func getTableStructure(c *gin.Context) {
	if !checkDBConnection(c) {
		return
	}

	tableName := c.Param("table")
	dbName := c.DefaultQuery("database", "")

	// 构建查询，获取更详细的列信息
	var query string
	if dbName != "" {
		// 如果指定了数据库，则查询该数据库中的表结构
		query = fmt.Sprintf(`
			SELECT 
				COLUMN_NAME, 
				DATA_TYPE,
				IS_NULLABLE,
				COLUMN_DEFAULT,
				COLUMN_KEY,
				EXTRA,
				CHARACTER_MAXIMUM_LENGTH,
				NUMERIC_PRECISION,
				NUMERIC_SCALE,
				COLUMN_TYPE,
				COLUMN_COMMENT
			FROM INFORMATION_SCHEMA.COLUMNS 
			WHERE TABLE_SCHEMA = '%s' AND TABLE_NAME = '%s'
			ORDER BY ORDINAL_POSITION
		`, dbName, tableName)
	} else {
		// 否则查询当前数据库的表结构
		query = fmt.Sprintf(`
			SELECT 
				COLUMN_NAME, 
				DATA_TYPE,
				IS_NULLABLE,
				COLUMN_DEFAULT,
				COLUMN_KEY,
				EXTRA,
				CHARACTER_MAXIMUM_LENGTH,
				NUMERIC_PRECISION,
				NUMERIC_SCALE,
				COLUMN_TYPE,
				COLUMN_COMMENT
			FROM INFORMATION_SCHEMA.COLUMNS 
			WHERE TABLE_NAME = '%s'
			ORDER BY ORDINAL_POSITION
		`, tableName)
	}

	// 执行查询
	rows, err := db.Raw(query).Rows()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "获取表结构失败: " + err.Error()})
		return
	}
	defer rows.Close()

	var columns []Column
	for rows.Next() {
		var (
			name             string
			dataType         string
			isNullable       string
			columnDefault    *string
			columnKey        string
			extra            string
			charMaxLength    *int64
			numericPrecision *int64
			numericScale     *int64
			columnType       string
			columnComment    string
		)

		if err := rows.Scan(
			&name,
			&dataType,
			&isNullable,
			&columnDefault,
			&columnKey,
			&extra,
			&charMaxLength,
			&numericPrecision,
			&numericScale,
			&columnType,
			&columnComment,
		); err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": "读取列信息失败: " + err.Error()})
			return
		}

		// 创建列对象
		column := Column{
			Name: name,
			Type: strings.ToUpper(dataType),
			Attributes: ColumnAttributes{
				NotNull:       isNullable == "NO",
				Unique:        columnKey == "UNI",
				PrimaryKey:    columnKey == "PRI",
				AutoIncrement: strings.Contains(extra, "auto_increment"),
			},
			Comment: columnComment, // 直接使用数据库中的注释
		}

		// 设置默认值
		if columnDefault != nil {
			column.Attributes.DefaultValue = *columnDefault
		} else {
			column.Attributes.DefaultValue = ""
		}

		// 设置长度和精度
		if charMaxLength != nil {
			column.Attributes.Length = fmt.Sprintf("%d", *charMaxLength)
		} else if numericPrecision != nil {
			column.Attributes.Length = fmt.Sprintf("%d", *numericPrecision)
			if numericScale != nil {
				column.Attributes.Scale = fmt.Sprintf("%d", *numericScale)
			}
		}

		// 检查是否为无符号类型
		column.Attributes.Unsigned = strings.Contains(columnType, "unsigned")

		columns = append(columns, column)
	}

	// 获取列注释信息
	descriptions, err := getTableColumnDescriptions(dbName, tableName)
	if err != nil {
		fmt.Printf("获取列注释失败: %v\n", err)
		// 继续执行，不中断流程
	}

	// 将注释信息添加到列对象中，如果数据库中的注释为空
	for i := range columns {
		if columns[i].Comment == "" {
			if desc, ok := descriptions[columns[i].Name]; ok {
				columns[i].Comment = desc
			} else {
				columns[i].Comment = columns[i].Name // 默认使用列名作为注释
			}
		}
	}

	c.JSON(http.StatusOK, columns)
}

// 更新表结构（添加新列）
func updateTableStructure(c *gin.Context) {
	if !checkDBConnection(c) {
		return
	}

	tableName := c.Param("table")
	dbName := c.DefaultQuery("database", "")

	// 构建表名，如果指定了数据库则包含数据库名
	fullTableName := tableName
	if dbName != "" {
		fullTableName = fmt.Sprintf("`%s`.`%s`", dbName, tableName)
	} else {
		fullTableName = fmt.Sprintf("`%s`", tableName)
	}

	var newColumn Column
	if err := c.ShouldBindJSON(&newColumn); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的列数据"})
		return
	}

	// 检查数据类型是否支持
	supportedTypes := map[string]string{
		// 字符串类型
		"TEXT":       "TEXT",
		"VARCHAR":    "VARCHAR(255)",
		"CHAR":       "CHAR(50)",
		"LONGTEXT":   "LONGTEXT",
		"MEDIUMTEXT": "MEDIUMTEXT",
		"TINYTEXT":   "TINYTEXT",
		// 数值类型
		"INTEGER":   "INT",
		"INT":       "INT",
		"BIGINT":    "BIGINT",
		"SMALLINT":  "SMALLINT",
		"TINYINT":   "TINYINT",
		"MEDIUMINT": "MEDIUMINT",
		"REAL":      "FLOAT",
		"FLOAT":     "FLOAT",
		"DOUBLE":    "DOUBLE",
		"DECIMAL":   "DECIMAL(10,2)",
		// 日期和时间类型
		"DATE":      "DATE",
		"TIME":      "TIME",
		"DATETIME":  "DATETIME",
		"TIMESTAMP": "TIMESTAMP",
		"YEAR":      "YEAR",
		// 布尔类型
		"BOOLEAN": "TINYINT(1)",
		// 二进制类型
		"BLOB":      "BLOB",
		"BINARY":    "BINARY(50)",
		"VARBINARY": "VARBINARY(255)",
		// JSON类型
		"JSON": "JSON",
	}

	baseType := strings.ToUpper(newColumn.Type)
	sqlType, ok := supportedTypes[baseType]
	if !ok {
		c.JSON(http.StatusBadRequest, gin.H{"error": "不支持的数据类型，支持的类型有：TEXT, VARCHAR, CHAR, LONGTEXT, MEDIUMTEXT, TINYTEXT, INTEGER, INT, BIGINT, SMALLINT, TINYINT, MEDIUMINT, REAL, FLOAT, DOUBLE, DECIMAL, DATE, TIME, DATETIME, TIMESTAMP, YEAR, BOOLEAN, BLOB, BINARY, VARBINARY, JSON"})
		return
	}

	// 根据属性修改SQL类型
	if baseType == "VARCHAR" && newColumn.Attributes.Length != "" {
		sqlType = fmt.Sprintf("VARCHAR(%s)", newColumn.Attributes.Length)
	} else if baseType == "CHAR" && newColumn.Attributes.Length != "" {
		sqlType = fmt.Sprintf("CHAR(%s)", newColumn.Attributes.Length)
	} else if baseType == "BINARY" && newColumn.Attributes.Length != "" {
		sqlType = fmt.Sprintf("BINARY(%s)", newColumn.Attributes.Length)
	} else if baseType == "VARBINARY" && newColumn.Attributes.Length != "" {
		sqlType = fmt.Sprintf("VARBINARY(%s)", newColumn.Attributes.Length)
	} else if baseType == "DECIMAL" {
		if newColumn.Attributes.Length != "" && newColumn.Attributes.Scale != "" {
			sqlType = fmt.Sprintf("DECIMAL(%s,%s)", newColumn.Attributes.Length, newColumn.Attributes.Scale)
		} else if newColumn.Attributes.Length != "" {
			sqlType = fmt.Sprintf("DECIMAL(%s)", newColumn.Attributes.Length)
		}
	}

	// 添加无符号属性
	if newColumn.Attributes.Unsigned && (baseType == "TINYINT" || baseType == "SMALLINT" || baseType == "MEDIUMINT" ||
		baseType == "INT" || baseType == "INTEGER" || baseType == "BIGINT" ||
		baseType == "FLOAT" || baseType == "DOUBLE" || baseType == "DECIMAL") {
		sqlType += " UNSIGNED"
	}

	// 检查表是否存在
	var hasTableQuery string
	if dbName != "" {
		hasTableQuery = fmt.Sprintf("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = '%s' AND table_name = '%s'", dbName, tableName)
	} else {
		hasTableQuery = fmt.Sprintf("SELECT COUNT(*) FROM information_schema.tables WHERE table_name = '%s'", tableName)
	}

	var tableCount int
	if err := db.Raw(hasTableQuery).Scan(&tableCount).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "检查表是否存在时出错: " + err.Error()})
		return
	}

	// 如果表不存在，则创建表
	if tableCount == 0 {
		if err := db.Exec(fmt.Sprintf("CREATE TABLE %s (id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY)", fullTableName)).Error; err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": "创建表失败: " + err.Error()})
			return
		}
		fmt.Printf("已创建表 %s\n", fullTableName)
	}

	// 检查列是否已存在
	var columnsQuery string
	if dbName != "" {
		columnsQuery = fmt.Sprintf("SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '%s' AND TABLE_NAME = '%s'", dbName, tableName)
	} else {
		columnsQuery = fmt.Sprintf("SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '%s'", tableName)
	}

	// 使用简单的字符串切片来存储列名
	var columnNames []string
	if err := db.Raw(columnsQuery).Pluck("COLUMN_NAME", &columnNames).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "获取列名失败: " + err.Error()})
		return
	}

	columnExists := false
	for _, existingName := range columnNames {
		if strings.EqualFold(existingName, newColumn.Name) {
			columnExists = true
			break
		}
	}

	if columnExists {
		c.JSON(http.StatusBadRequest, gin.H{"error": "列名已存在"})
		return
	}

	// 构建完整的列定义
	columnDefinition := fmt.Sprintf("%s %s", newColumn.Name, sqlType)

	// 添加NOT NULL约束
	if newColumn.Attributes.NotNull {
		columnDefinition += " NOT NULL"
	}

	// 添加默认值
	if newColumn.Attributes.DefaultValue != "" {
		// 检查是否为不能设置默认值的类型
		canHaveDefault := true
		noDefaultTypes := []string{"TEXT", "LONGTEXT", "MEDIUMTEXT", "TINYTEXT", "BLOB", "GEOMETRY", "JSON"}
		for _, noDefaultType := range noDefaultTypes {
			if baseType == noDefaultType {
				canHaveDefault = false
				break
			}
		}

		if canHaveDefault {
			// 对字符串类型的默认值添加引号
			if baseType == "VARCHAR" || baseType == "CHAR" || baseType == "DATE" ||
				baseType == "TIME" || baseType == "DATETIME" || baseType == "TIMESTAMP" ||
				baseType == "YEAR" {
				columnDefinition += fmt.Sprintf(" DEFAULT '%s'", newColumn.Attributes.DefaultValue)
			} else {
				columnDefinition += fmt.Sprintf(" DEFAULT %s", newColumn.Attributes.DefaultValue)
			}
		}
	}

	// 添加自动递增
	if newColumn.Attributes.AutoIncrement {
		columnDefinition += " AUTO_INCREMENT"
	}

	// 添加唯一约束
	if newColumn.Attributes.Unique {
		columnDefinition += " UNIQUE"
	}

	// 添加主键约束
	if newColumn.Attributes.PrimaryKey {
		columnDefinition += " PRIMARY KEY"
	}

	// 添加注释
	if newColumn.Comment != "" {
		columnDefinition += fmt.Sprintf(" COMMENT '%s'", strings.ReplaceAll(newColumn.Comment, "'", "\\'"))
	}

	// 添加新列
	query := fmt.Sprintf("ALTER TABLE %s ADD COLUMN %s", fullTableName, columnDefinition)
	if err := db.Exec(query).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "添加列失败: " + err.Error()})
		return
	}

	// 保存列注释到自定义表中，作为备份
	if err := saveColumnDescription(dbName, tableName, newColumn.Name, newColumn.Comment); err != nil {
		fmt.Printf("保存列注释失败: %v\n", err)
		// 继续执行，不中断流程
	}

	c.JSON(http.StatusOK, gin.H{"message": "列添加成功"})
}

// 获取所有数据
func getData(c *gin.Context) {
	if !checkDBConnection(c) {
		return
	}

	tableName := c.Param("table")
	dbName := c.DefaultQuery("database", "")

	// 获取查询参数
	idParam := c.DefaultQuery("id", "")
	nameParam := c.DefaultQuery("name", "")     // 添加name参数支持
	limitParam := c.DefaultQuery("limit", "20") // 默认限制为20条
	pageParam := c.DefaultQuery("page", "1")    // 默认第1页

	// 解析分页参数
	limit, err := strconv.Atoi(limitParam)
	if err != nil || limit <= 0 {
		limit = 20 // 默认每页20条
	}
	// 限制最大返回条数为100，避免过大的查询
	if limit > 100 {
		limit = 100
	}

	page, err := strconv.Atoi(pageParam)
	if err != nil || page <= 0 {
		page = 1
	}

	// 计算偏移量
	offset := (page - 1) * limit

	// 构建表名，如果指定了数据库则包含数据库名
	fullTableName := tableName
	if dbName != "" {
		fullTableName = fmt.Sprintf("%s.%s", dbName, tableName)
	}

	// 获取表结构
	var columnsQuery string
	if dbName != "" {
		columnsQuery = fmt.Sprintf("SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '%s' AND TABLE_NAME = '%s' ORDER BY ORDINAL_POSITION", dbName, tableName)
	} else {
		columnsQuery = fmt.Sprintf("SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '%s' ORDER BY ORDINAL_POSITION", tableName)
	}

	// 使用简单的字符串切片来存储列名
	var columnNames []string
	if err := db.Raw(columnsQuery).Pluck("COLUMN_NAME", &columnNames).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "获取列名失败: " + err.Error()})
		return
	}

	// 如果没有找到列，返回错误
	if len(columnNames) == 0 {
		c.JSON(http.StatusBadRequest, gin.H{"error": "表结构为空或表不存在"})
		return
	}

	// 构建查询SQL，明确指定列名而不是使用SELECT *
	var query string
	var countQuery string
	var args []interface{}
	var countArgs []interface{}

	// 基础查询，使用明确的列名
	// 为每个列名添加反引号，防止SQL注入和关键字冲突
	quotedColumnNames := make([]string, len(columnNames))
	for i, col := range columnNames {
		quotedColumnNames[i] = fmt.Sprintf("`%s`", col)
	}

	query = fmt.Sprintf("SELECT %s FROM %s", strings.Join(quotedColumnNames, ", "), fullTableName)
	countQuery = fmt.Sprintf("SELECT COUNT(*) FROM %s", fullTableName)

	// 检查表是否有name字段
	hasNameField := false
	for _, col := range columnNames {
		if strings.ToLower(col) == "name" {
			hasNameField = true
			break
		}
	}

	// 构建WHERE条件
	whereAdded := false

	// 如果指定了ID，添加WHERE条件
	if idParam != "" {
		query += " WHERE `id` = ?"
		countQuery += " WHERE `id` = ?"
		args = append(args, idParam)
		countArgs = append(countArgs, idParam)
		whereAdded = true
	}

	// 如果指定了name且表中有name字段，添加WHERE条件
	if nameParam != "" && hasNameField {
		if whereAdded {
			query += " AND `name` LIKE ?"
			countQuery += " AND `name` LIKE ?"
		} else {
			query += " WHERE `name` LIKE ?"
			countQuery += " WHERE `name` LIKE ?"
			whereAdded = true
		}
		// 使用正确的SQL语法格式化参数
		likePattern := "%" + nameParam + "%"
		args = append(args, likePattern)
		countArgs = append(countArgs, likePattern)
	}

	// 处理多条件筛选
	for i := 0; ; i++ {
		// 获取字段、操作符和值
		fieldKey := fmt.Sprintf("field%d", i)
		opKey := fmt.Sprintf("op%d", i)
		valueKey := fmt.Sprintf("value%d", i)

		fieldParam := c.DefaultQuery(fieldKey, "")
		opParam := c.DefaultQuery(opKey, "")
		valueParam := c.DefaultQuery(valueKey, "")

		// 如果没有找到对应索引的参数，说明已处理完所有多条件筛选
		if fieldParam == "" || opParam == "" || valueParam == "" {
			break
		}

		// 检查字段是否存在于当前表
		fieldExists := false
		for _, col := range columnNames {
			if strings.ToLower(col) == strings.ToLower(fieldParam) {
				fieldExists = true
				break
			}
		}

		if !fieldExists {
			continue // 忽略不存在的字段
		}

		// 根据操作符构建WHERE条件
		var condition string
		switch strings.ToLower(opParam) {
		case "eq":
			condition = fmt.Sprintf("`%s` = ?", fieldParam)
			args = append(args, valueParam)
			countArgs = append(countArgs, valueParam)
		case "ne":
			condition = fmt.Sprintf("`%s` != ?", fieldParam)
			args = append(args, valueParam)
			countArgs = append(countArgs, valueParam)
		case "gt":
			condition = fmt.Sprintf("`%s` > ?", fieldParam)
			args = append(args, valueParam)
			countArgs = append(countArgs, valueParam)
		case "lt":
			condition = fmt.Sprintf("`%s` < ?", fieldParam)
			args = append(args, valueParam)
			countArgs = append(countArgs, valueParam)
		case "like":
			condition = fmt.Sprintf("`%s` LIKE ?", fieldParam)
			args = append(args, "%"+valueParam+"%")
			countArgs = append(countArgs, "%"+valueParam+"%")
		default:
			continue // 忽略不支持的操作符
		}

		// 添加条件到查询语句
		if whereAdded {
			query += " AND " + condition
			countQuery += " AND " + condition
		} else {
			query += " WHERE " + condition
			countQuery += " WHERE " + condition
			whereAdded = true
		}
	}

	// 添加排序
	query += " ORDER BY id DESC" // 降序排列，最新的数据在前面

	// 添加分页
	if idParam == "" {
		query += " LIMIT ? OFFSET ?"
		args = append(args, limit, offset)
	}

	// 记录查询开始时间，用于计算查询耗时
	startTime := time.Now()

	// 获取总记录数
	var totalCount int64
	if err := db.Raw(countQuery, countArgs...).Scan(&totalCount).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "获取总记录数失败: " + err.Error()})
		return
	}

	// 执行查询
	rows, err := db.Raw(query, args...).Rows()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	defer rows.Close()

	// 计算查询耗时
	queryTime := time.Since(startTime)
	fmt.Printf("查询耗时: %v, SQL: %s\n", queryTime, query)

	// 获取列名
	columnNames, err = rows.Columns()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "获取列名失败: " + err.Error()})
		return
	}

	var results []DynamicTable
	for rows.Next() {
		data := DynamicTable{Fields: make(map[string]interface{})}

		// 创建扫描目标
		scanTargets := make([]interface{}, len(columnNames))
		for i := range scanTargets {
			scanTargets[i] = new(interface{})
		}

		// 扫描数据
		if err := rows.Scan(scanTargets...); err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": "扫描数据失败: " + err.Error()})
			return
		}

		// 处理所有字段
		for i, colName := range columnNames {
			if strings.ToLower(colName) == "id" {
				if idPtr, ok := scanTargets[i].(*interface{}); ok {
					// 处理不同类型的ID
					switch v := (*idPtr).(type) {
					case int64:
						data.ID = uint(v)
					case int:
						data.ID = uint(v)
					case uint:
						data.ID = v
					case uint64:
						data.ID = uint(v)
					case float64:
						data.ID = uint(v)
					case string:
						// 尝试将字符串转换为整数
						if id, err := strconv.ParseUint(v, 10, 64); err == nil {
							data.ID = uint(id)
						}
					case []uint8:
						// 处理字节数组（MySQL常见类型）
						idStr := string(v)
						if id, err := strconv.ParseUint(idStr, 10, 64); err == nil {
							data.ID = uint(id)
						} else {
							fmt.Printf("无法将字节数组转换为ID: %v, 错误: %v\n", v, err)
						}
					default:
						// 记录无法识别的ID类型
						fmt.Printf("未知ID类型: %T, 值: %v\n", *idPtr, *idPtr)
					}
				}
			} else {
				if valPtr, ok := scanTargets[i].(*interface{}); ok {
					// 处理字段值，如果是字节数组，转换为字符串
					switch v := (*valPtr).(type) {
					case []uint8:
						// MySQL中的字符串通常以字节数组形式返回
						data.Fields[colName] = string(v)
					default:
						data.Fields[colName] = *valPtr
					}
				}
			}
		}
		results = append(results, data)
	}

	// 返回分页信息和数据
	c.JSON(http.StatusOK, gin.H{
		"data": results,
		"pagination": gin.H{
			"total": totalCount,
			"page":  page,
			"limit": limit,
			"pages": int(math.Ceil(float64(totalCount) / float64(limit))),
		},
		"queryTime": queryTime.String(),
	})
}

// 创建数据
func createData(c *gin.Context) {
	if !checkDBConnection(c) {
		return
	}

	tableName := c.Param("table")
	dbName := c.DefaultQuery("database", "")

	// 构建表名，如果指定了数据库则包含数据库名
	fullTableName := tableName
	if dbName != "" {
		fullTableName = fmt.Sprintf("%s.%s", dbName, tableName)
	}

	var data DynamicTable
	if err := c.ShouldBindJSON(&data); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid data"})
		return
	}

	// 获取表结构
	var columnsQuery string
	if dbName != "" {
		columnsQuery = fmt.Sprintf("SELECT COLUMN_NAME as name, DATA_TYPE as type FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '%s' AND TABLE_NAME = '%s'", dbName, tableName)
	} else {
		columnsQuery = fmt.Sprintf("SELECT COLUMN_NAME as name, DATA_TYPE as type FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '%s'", tableName)
	}

	var columns []Column
	if err := db.Raw(columnsQuery).Scan(&columns).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	// 构造插入语句
	placeholders := []string{}
	values := []interface{}{}

	// 创建列名到类型的映射
	columnTypes := make(map[string]string)
	for _, col := range columns {
		columnTypes[strings.ToLower(col.Name)] = strings.ToLower(col.Type)
	}

	for _, col := range columns {
		if strings.ToLower(col.Name) == "id" {
			continue
		}

		// 尝试以不区分大小写的方式查找字段值
		var fieldValue interface{}
		var found bool

		// 直接使用列名
		if val, ok := data.Fields[col.Name]; ok {
			fieldValue = val
			found = true
		} else {
			// 尝试查找不区分大小写的字段名
			for key, val := range data.Fields {
				if strings.ToLower(key) == strings.ToLower(col.Name) {
					fieldValue = val
					found = true
					break
				}
			}
		}

		if found {
			// 根据列类型转换值
			colType := strings.ToLower(col.Type)
			switch colType {
			case "int", "bigint", "tinyint", "smallint", "mediumint", "integer":
				// 如果是字符串，尝试转换为整数
				if strVal, ok := fieldValue.(string); ok {
					if strVal == "" {
						// 空字符串转为0
						fieldValue = 0
					} else if intVal, err := strconv.ParseInt(strVal, 10, 64); err == nil {
						fieldValue = intVal
					}
				}
			case "decimal", "float", "double", "real":
				// 如果是字符串，尝试转换为浮点数
				if strVal, ok := fieldValue.(string); ok {
					if strVal == "" {
						// 空字符串转为0.0
						fieldValue = 0.0
					} else if floatVal, err := strconv.ParseFloat(strVal, 64); err == nil {
						fieldValue = floatVal
					}
				}
			}

			placeholders = append(placeholders, fmt.Sprintf("`%s`", col.Name))
			values = append(values, fieldValue)
		}
	}

	if len(placeholders) == 0 {
		c.JSON(http.StatusBadRequest, gin.H{"error": "No valid fields provided"})
		return
	}

	// 使用事务来确保数据一致性
	tx := db.Begin()
	if tx.Error != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "开始事务失败: " + tx.Error.Error()})
		return
	}

	// 构建插入SQL
	query := fmt.Sprintf("INSERT INTO %s (%s) VALUES (%s)",
		fullTableName,
		strings.Join(placeholders, ","),
		strings.Join(strings.Split(strings.Repeat("?", len(placeholders)), ""), ","))

	fmt.Printf("执行SQL: %s, 参数: %v\n", query, values)

	// 执行插入
	result := tx.Exec(query, values...)
	if result.Error != nil {
		tx.Rollback()
		c.JSON(http.StatusInternalServerError, gin.H{"error": "插入数据失败: " + result.Error.Error()})
		return
	}

	// 获取插入的ID
	var lastInsertID int64
	if dbName != "" {
		tx.Raw("SELECT LAST_INSERT_ID()").Scan(&lastInsertID)
	} else {
		tx.Raw("SELECT LAST_INSERT_ID()").Scan(&lastInsertID)
	}

	// 提交事务
	if err := tx.Commit().Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "提交事务失败: " + err.Error()})
		return
	}

	// 构建返回的数据对象
	newData := DynamicTable{
		ID:     uint(lastInsertID),
		Fields: data.Fields,
	}

	// 返回新创建的数据
	c.JSON(http.StatusOK, gin.H{
		"message": "数据创建成功",
		"data":    newData,
	})
}

// 更新数据
func updateData(c *gin.Context) {
	if !checkDBConnection(c) {
		return
	}

	tableName := c.Param("table")
	id := c.Param("id")
	dbName := c.DefaultQuery("database", "")

	// 构建表名，如果指定了数据库则包含数据库名
	fullTableName := tableName
	if dbName != "" {
		fullTableName = fmt.Sprintf("%s.%s", dbName, tableName)
	}

	var data DynamicTable
	if err := c.ShouldBindJSON(&data); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid data"})
		return
	}

	// 获取表结构 - 使用简单的字符串切片而不是Column结构体
	var columnsQuery string
	if dbName != "" {
		columnsQuery = fmt.Sprintf("SELECT COLUMN_NAME as name, DATA_TYPE as type FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '%s' AND TABLE_NAME = '%s'", dbName, tableName)
	} else {
		columnsQuery = fmt.Sprintf("SELECT COLUMN_NAME as name, DATA_TYPE as type FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '%s'", tableName)
	}

	// 使用简单的结构体来存储列信息
	type SimpleColumn struct {
		Name string
		Type string
	}

	var columns []SimpleColumn
	if err := db.Raw(columnsQuery).Scan(&columns).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	// 构造更新语句
	updates := []string{}
	values := []interface{}{}

	// 创建列名到类型的映射
	columnTypes := make(map[string]string)
	for _, col := range columns {
		columnTypes[strings.ToLower(col.Name)] = strings.ToLower(col.Type)
	}

	for _, col := range columns {
		if strings.ToLower(col.Name) == "id" {
			continue
		}

		// 尝试以不区分大小写的方式查找字段值
		var fieldValue interface{}
		var found bool

		// 直接使用列名
		if val, ok := data.Fields[col.Name]; ok {
			fieldValue = val
			found = true
		} else {
			// 尝试查找不区分大小写的字段名
			for key, val := range data.Fields {
				if strings.ToLower(key) == strings.ToLower(col.Name) {
					fieldValue = val
					found = true
					break
				}
			}
		}

		if found {
			// 根据列类型转换值
			colType := strings.ToLower(col.Type)
			switch colType {
			case "int", "bigint", "tinyint", "smallint", "mediumint", "integer":
				// 如果是字符串，尝试转换为整数
				if strVal, ok := fieldValue.(string); ok {
					if strVal == "" {
						// 空字符串转为0
						fieldValue = 0
					} else if intVal, err := strconv.ParseInt(strVal, 10, 64); err == nil {
						fieldValue = intVal
					}
				}
			case "decimal", "float", "double", "real":
				// 如果是字符串，尝试转换为浮点数
				if strVal, ok := fieldValue.(string); ok {
					if strVal == "" {
						// 空字符串转为0.0
						fieldValue = 0.0
					} else if floatVal, err := strconv.ParseFloat(strVal, 64); err == nil {
						fieldValue = floatVal
					}
				}
			}

			updates = append(updates, fmt.Sprintf("`%s` = ?", col.Name))
			values = append(values, fieldValue)
		}
	}

	if len(updates) == 0 {
		c.JSON(http.StatusBadRequest, gin.H{"error": "No valid fields provided"})
		return
	}

	values = append(values, id)
	query := fmt.Sprintf("UPDATE %s SET %s WHERE id = ?",
		fullTableName,
		strings.Join(updates, ","))

	fmt.Printf("执行SQL: %s, 参数: %v\n", query, values)

	if err := db.Exec(query, values...).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "Data updated successfully"})
}

// 删除数据
func deleteData(c *gin.Context) {
	if !checkDBConnection(c) {
		return
	}

	tableName := c.Param("table")
	id := c.Param("id")
	dbName := c.DefaultQuery("database", "")

	// 构建表名，如果指定了数据库则包含数据库名
	fullTableName := tableName
	if dbName != "" {
		fullTableName = fmt.Sprintf("%s.%s", dbName, tableName)
	}

	if err := db.Exec(fmt.Sprintf("DELETE FROM %s WHERE id = ?", fullTableName), id).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	c.JSON(http.StatusOK, gin.H{"message": "Data deleted successfully"})
}

// 删除列
func deleteColumn(c *gin.Context) {
	if !checkDBConnection(c) {
		return
	}

	tableName := c.Param("table")
	columnName := c.Param("column")
	dbName := c.DefaultQuery("database", "")

	// 构建表名，如果指定了数据库则包含数据库名
	fullTableName := tableName
	if dbName != "" {
		fullTableName = fmt.Sprintf("%s.%s", dbName, tableName)
	}

	// 检查表是否存在
	var hasTableQuery string
	if dbName != "" {
		hasTableQuery = fmt.Sprintf("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = '%s' AND table_name = '%s'", dbName, tableName)
	} else {
		hasTableQuery = fmt.Sprintf("SELECT COUNT(*) FROM information_schema.tables WHERE table_name = '%s'", tableName)
	}

	var count int
	if err := db.Raw(hasTableQuery).Scan(&count).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	if count == 0 {
		c.JSON(http.StatusBadRequest, gin.H{"error": "表不存在"})
		return
	}

	// 检查列是否存在
	var columnsQuery string
	if dbName != "" {
		columnsQuery = fmt.Sprintf("SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '%s' AND TABLE_NAME = '%s'", dbName, tableName)
	} else {
		columnsQuery = fmt.Sprintf("SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '%s'", tableName)
	}

	// 使用简单的字符串切片来存储列名
	var columnNames []string
	if err := db.Raw(columnsQuery).Pluck("COLUMN_NAME", &columnNames).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "获取列名失败: " + err.Error()})
		return
	}

	columnExists := false
	for _, existingName := range columnNames {
		if strings.EqualFold(existingName, columnName) {
			columnExists = true
			break
		}
	}

	if !columnExists {
		c.JSON(http.StatusBadRequest, gin.H{"error": "列不存在"})
		return
	}

	// 不允许删除ID列
	if strings.EqualFold(columnName, "id") {
		c.JSON(http.StatusBadRequest, gin.H{"error": "不能删除ID列"})
		return
	}

	// 执行删除列操作
	query := fmt.Sprintf("ALTER TABLE %s DROP COLUMN %s", fullTableName, columnName)
	if err := db.Exec(query).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	// 删除列注释
	if err := db.Where("database_name = ? AND table_name = ? AND column_name = ?",
		dbName, tableName, columnName).Delete(&ColumnDescription{}).Error; err != nil {
		fmt.Printf("删除列注释失败: %v\n", err)
		// 继续执行，不中断流程
	}

	// 返回成功消息，不包含任何数据查询
	c.JSON(http.StatusOK, gin.H{
		"message": "列删除成功",
		"column":  columnName,
		"table":   tableName,
	})
}

// 更改列名
func renameColumn(c *gin.Context) {
	if !checkDBConnection(c) {
		return
	}

	tableName := c.Param("table")
	oldColumnName := c.Param("column")
	dbName := c.DefaultQuery("database", "")

	// 构建表名，如果指定了数据库则包含数据库名
	fullTableName := tableName
	if dbName != "" {
		fullTableName = fmt.Sprintf("%s.%s", dbName, tableName)
	}

	var requestData struct {
		NewName string `json:"newName"`
	}

	if err := c.ShouldBindJSON(&requestData); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的请求数据"})
		return
	}

	newColumnName := requestData.NewName

	// 检查表是否存在
	var hasTableQuery string
	if dbName != "" {
		hasTableQuery = fmt.Sprintf("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = '%s' AND table_name = '%s'", dbName, tableName)
	} else {
		hasTableQuery = fmt.Sprintf("SELECT COUNT(*) FROM information_schema.tables WHERE table_name = '%s'", tableName)
	}

	var count int
	if err := db.Raw(hasTableQuery).Scan(&count).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	if count == 0 {
		c.JSON(http.StatusBadRequest, gin.H{"error": "表不存在"})
		return
	}

	// 检查旧列是否存在
	var columnsQuery string
	if dbName != "" {
		columnsQuery = fmt.Sprintf("SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '%s' AND TABLE_NAME = '%s'", dbName, tableName)
	} else {
		columnsQuery = fmt.Sprintf("SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '%s'", tableName)
	}

	// 使用简单的字符串切片来存储列名
	var columnNames []string
	if err := db.Raw(columnsQuery).Pluck("COLUMN_NAME", &columnNames).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "获取列名失败: " + err.Error()})
		return
	}

	oldColumnExists := false
	for _, existingName := range columnNames {
		if strings.EqualFold(existingName, oldColumnName) {
			oldColumnExists = true
			break
		}
	}

	if !oldColumnExists {
		c.JSON(http.StatusBadRequest, gin.H{"error": "原列不存在"})
		return
	}

	// 检查新列名是否已存在
	for _, existingName := range columnNames {
		if strings.EqualFold(existingName, newColumnName) {
			c.JSON(http.StatusBadRequest, gin.H{"error": "新列名已存在"})
			return
		}
	}

	// 不允许重命名ID列
	if strings.EqualFold(oldColumnName, "id") {
		c.JSON(http.StatusBadRequest, gin.H{"error": "不能重命名ID列"})
		return
	}

	// 获取列的数据类型和注释
	var columnTypeQuery string
	if dbName != "" {
		columnTypeQuery = fmt.Sprintf("SELECT DATA_TYPE, COLUMN_TYPE, COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '%s' AND TABLE_NAME = '%s' AND COLUMN_NAME = '%s'", dbName, tableName, oldColumnName)
	} else {
		columnTypeQuery = fmt.Sprintf("SELECT DATA_TYPE, COLUMN_TYPE, COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '%s' AND COLUMN_NAME = '%s'", tableName, oldColumnName)
	}

	var dataType, columnType, columnComment string
	if err := db.Raw(columnTypeQuery).Row().Scan(&dataType, &columnType, &columnComment); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "获取列类型失败: " + err.Error()})
		return
	}

	// 执行重命名列操作，保留注释
	var query string
	if columnComment != "" {
		query = fmt.Sprintf("ALTER TABLE %s CHANGE COLUMN %s %s %s COMMENT '%s'",
			fullTableName, oldColumnName, newColumnName, columnType, strings.ReplaceAll(columnComment, "'", "\\'"))
	} else {
		query = fmt.Sprintf("ALTER TABLE %s CHANGE COLUMN %s %s %s",
			fullTableName, oldColumnName, newColumnName, columnType)
	}

	if err := db.Exec(query).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	// 更新列注释到自定义表中，作为备份
	if err := saveColumnDescription(dbName, tableName, newColumnName, columnComment); err != nil {
		fmt.Printf("更新列注释失败: %v\n", err)
		// 继续执行，不中断流程
	}

	c.JSON(http.StatusOK, gin.H{"message": "列重命名成功"})
}

// 修改列属性
func updateColumnAttributes(c *gin.Context) {
	if !checkDBConnection(c) {
		return
	}

	tableName := c.Param("table")
	columnName := c.Param("column")
	dbName := c.DefaultQuery("database", "")

	// 构建表名，如果指定了数据库则包含数据库名
	fullTableName := tableName
	if dbName != "" {
		fullTableName = fmt.Sprintf("%s.%s", dbName, tableName)
	}

	var columnData Column
	if err := c.ShouldBindJSON(&columnData); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的列数据"})
		return
	}

	// 检查表是否存在
	var hasTableQuery string
	if dbName != "" {
		hasTableQuery = fmt.Sprintf("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = '%s' AND table_name = '%s'", dbName, tableName)
	} else {
		hasTableQuery = fmt.Sprintf("SELECT COUNT(*) FROM information_schema.tables WHERE table_name = '%s'", tableName)
	}

	var count int
	if err := db.Raw(hasTableQuery).Scan(&count).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	if count == 0 {
		c.JSON(http.StatusBadRequest, gin.H{"error": "表不存在"})
		return
	}

	// 检查列是否存在
	var columnsQuery string
	if dbName != "" {
		columnsQuery = fmt.Sprintf("SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '%s' AND TABLE_NAME = '%s'", dbName, tableName)
	} else {
		columnsQuery = fmt.Sprintf("SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '%s'", tableName)
	}

	var columnNames []string
	if err := db.Raw(columnsQuery).Pluck("COLUMN_NAME", &columnNames).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "获取列名失败: " + err.Error()})
		return
	}

	columnExists := false
	for _, existingName := range columnNames {
		if strings.EqualFold(existingName, columnName) {
			columnExists = true
			break
		}
	}

	if !columnExists {
		c.JSON(http.StatusBadRequest, gin.H{"error": "列不存在"})
		return
	}

	// 不允许修改ID列
	if strings.EqualFold(columnName, "id") {
		c.JSON(http.StatusBadRequest, gin.H{"error": "不能修改ID列"})
		return
	}

	// 检查数据类型是否支持
	supportedTypes := map[string]string{
		// 字符串类型
		"TEXT":       "TEXT",
		"VARCHAR":    "VARCHAR(255)",
		"CHAR":       "CHAR(50)",
		"LONGTEXT":   "LONGTEXT",
		"MEDIUMTEXT": "MEDIUMTEXT",
		"TINYTEXT":   "TINYTEXT",
		// 数值类型
		"INTEGER":   "INT",
		"INT":       "INT",
		"BIGINT":    "BIGINT",
		"SMALLINT":  "SMALLINT",
		"TINYINT":   "TINYINT",
		"MEDIUMINT": "MEDIUMINT",
		"REAL":      "FLOAT",
		"FLOAT":     "FLOAT",
		"DOUBLE":    "DOUBLE",
		"DECIMAL":   "DECIMAL(10,2)",
		// 日期和时间类型
		"DATE":      "DATE",
		"TIME":      "TIME",
		"DATETIME":  "DATETIME",
		"TIMESTAMP": "TIMESTAMP",
		"YEAR":      "YEAR",
		// 布尔类型
		"BOOLEAN": "TINYINT(1)",
		// 二进制类型
		"BLOB":      "BLOB",
		"BINARY":    "BINARY(50)",
		"VARBINARY": "VARBINARY(255)",
		// JSON类型
		"JSON": "JSON",
	}

	baseType := strings.ToUpper(columnData.Type)
	sqlType, ok := supportedTypes[baseType]
	if !ok {
		c.JSON(http.StatusBadRequest, gin.H{"error": "不支持的数据类型，支持的类型有：TEXT, VARCHAR, CHAR, LONGTEXT, MEDIUMTEXT, TINYTEXT, INTEGER, INT, BIGINT, SMALLINT, TINYINT, MEDIUMINT, REAL, FLOAT, DOUBLE, DECIMAL, DATE, TIME, DATETIME, TIMESTAMP, YEAR, BOOLEAN, BLOB, BINARY, VARBINARY, JSON"})
		return
	}

	// 根据属性修改SQL类型
	if baseType == "VARCHAR" && columnData.Attributes.Length != "" {
		sqlType = fmt.Sprintf("VARCHAR(%s)", columnData.Attributes.Length)
	} else if baseType == "CHAR" && columnData.Attributes.Length != "" {
		sqlType = fmt.Sprintf("CHAR(%s)", columnData.Attributes.Length)
	} else if baseType == "BINARY" && columnData.Attributes.Length != "" {
		sqlType = fmt.Sprintf("BINARY(%s)", columnData.Attributes.Length)
	} else if baseType == "VARBINARY" && columnData.Attributes.Length != "" {
		sqlType = fmt.Sprintf("VARBINARY(%s)", columnData.Attributes.Length)
	} else if baseType == "DECIMAL" {
		if columnData.Attributes.Length != "" && columnData.Attributes.Scale != "" {
			sqlType = fmt.Sprintf("DECIMAL(%s,%s)", columnData.Attributes.Length, columnData.Attributes.Scale)
		} else if columnData.Attributes.Length != "" {
			sqlType = fmt.Sprintf("DECIMAL(%s)", columnData.Attributes.Length)
		}
	}

	// 添加无符号属性
	if columnData.Attributes.Unsigned && (baseType == "TINYINT" || baseType == "SMALLINT" || baseType == "MEDIUMINT" ||
		baseType == "INT" || baseType == "INTEGER" || baseType == "BIGINT" ||
		baseType == "FLOAT" || baseType == "DOUBLE" || baseType == "DECIMAL") {
		sqlType += " UNSIGNED"
	}

	// 构建完整的列定义
	columnDefinition := fmt.Sprintf("%s %s", columnData.Name, sqlType)

	// 添加NOT NULL约束
	if columnData.Attributes.NotNull {
		columnDefinition += " NOT NULL"
	} else {
		columnDefinition += " NULL"
	}

	// 添加默认值
	if columnData.Attributes.DefaultValue != "" {
		// 检查是否为不能设置默认值的类型
		canHaveDefault := true
		noDefaultTypes := []string{"TEXT", "LONGTEXT", "MEDIUMTEXT", "TINYTEXT", "BLOB", "GEOMETRY", "JSON"}
		for _, noDefaultType := range noDefaultTypes {
			if baseType == noDefaultType {
				canHaveDefault = false
				break
			}
		}

		if canHaveDefault {
			// 对字符串类型的默认值添加引号
			if baseType == "VARCHAR" || baseType == "CHAR" || baseType == "DATE" ||
				baseType == "TIME" || baseType == "DATETIME" || baseType == "TIMESTAMP" ||
				baseType == "YEAR" {
				columnDefinition += fmt.Sprintf(" DEFAULT '%s'", columnData.Attributes.DefaultValue)
			} else {
				columnDefinition += fmt.Sprintf(" DEFAULT %s", columnData.Attributes.DefaultValue)
			}
		}
	}

	// 添加自动递增
	if columnData.Attributes.AutoIncrement {
		columnDefinition += " AUTO_INCREMENT"
	}

	// 添加唯一约束
	if columnData.Attributes.Unique {
		columnDefinition += " UNIQUE"
	}

	// 添加注释
	if columnData.Comment != "" {
		columnDefinition += fmt.Sprintf(" COMMENT '%s'", strings.ReplaceAll(columnData.Comment, "'", "\\'"))
	}

	// 执行修改列操作
	var query string
	if columnData.Name != columnName {
		// 如果列名也要修改，使用CHANGE COLUMN
		query = fmt.Sprintf("ALTER TABLE %s CHANGE COLUMN %s %s",
			fullTableName, columnName, columnDefinition)
	} else {
		// 如果只修改属性，使用MODIFY COLUMN
		query = fmt.Sprintf("ALTER TABLE %s MODIFY COLUMN %s",
			fullTableName, columnDefinition)
	}

	if err := db.Exec(query).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "修改列失败: " + err.Error()})
		return
	}

	// 更新列注释到自定义表中，作为备份
	if err := saveColumnDescription(dbName, tableName, columnData.Name, columnData.Comment); err != nil {
		fmt.Printf("更新列注释失败: %v\n", err)
		// 继续执行，不中断流程
	}

	c.JSON(http.StatusOK, gin.H{"message": "列修改成功"})
}

// 创建新表
func createTable(c *gin.Context) {
	if !checkDBConnection(c) {
		return
	}

	var requestData struct {
		TableName string `json:"table_name"`
		SQL       string `json:"sql"`
	}

	if err := c.ShouldBindJSON(&requestData); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的请求数据"})
		return
	}

	dbName := c.DefaultQuery("database", "")
	if dbName == "" {
		dbName = dbConfig.DBName
	}

	// 根据是否提供SQL来创建表
	var err error
	if requestData.SQL != "" {
		// 使用提供的SQL创建表
		// 为安全起见，我们应该验证SQL是否包含CREATE TABLE语句
		sqlLower := strings.ToLower(requestData.SQL)
		if !strings.Contains(sqlLower, "create table") {
			c.JSON(http.StatusBadRequest, gin.H{"error": "SQL必须包含CREATE TABLE语句"})
			return
		}

		// 如果没有提供表名，尝试从SQL中提取
		if requestData.TableName == "" {
			// 提取表名的正则表达式
			re := regexp.MustCompile(`(?i)create\s+table\s+(?:if\s+not\s+exists\s+)?(?:` + dbName + `\.)?[` + "`" + `"]?([a-zA-Z0-9_]+)[` + "`" + `"]?`)
			matches := re.FindStringSubmatch(requestData.SQL)
			if len(matches) > 1 {
				requestData.TableName = matches[1]
				fmt.Printf("从SQL中提取的表名: %s\n", requestData.TableName)
			} else {
				c.JSON(http.StatusBadRequest, gin.H{"error": "无法从SQL中提取表名，请手动输入表名"})
				return
			}
		}

		// 将SQL语句按分号分割，逐条执行
		sqlStatements := strings.Split(requestData.SQL, ";")
		for _, stmt := range sqlStatements {
			// 跳过空语句
			stmt = strings.TrimSpace(stmt)
			if stmt == "" {
				continue
			}

			// 执行单条SQL语句
			fmt.Printf("执行SQL语句: %s\n", stmt)
			if err := db.Exec(stmt).Error; err != nil {
				c.JSON(http.StatusInternalServerError, gin.H{"error": "创建表失败: " + err.Error()})
				return
			}
		}
	} else {
		// 如果没有提供SQL，则必须提供表名
		if requestData.TableName == "" {
			c.JSON(http.StatusBadRequest, gin.H{"error": "创建表时必须提供表名或SQL语句"})
			return
		}

		// 创建一个只有ID列的空表
		createTableSQL := fmt.Sprintf("CREATE TABLE %s.%s (id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY COMMENT '主键ID')", dbName, requestData.TableName)
		err = db.Exec(createTableSQL).Error
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": "创建表失败: " + err.Error()})
			return
		}
	}

	c.JSON(http.StatusOK, gin.H{
		"message":    "表创建成功",
		"table_name": requestData.TableName,
	})
}

// 保存列注释
func saveColumnDescription(dbName, tableName, columnName, comment string) error {
	if db == nil {
		return fmt.Errorf("数据库未连接")
	}

	// 如果注释为空，则使用列名作为注释
	if comment == "" {
		comment = columnName
	}

	// 查找是否已存在注释
	var desc ColumnDescription
	result := db.Where("database_name = ? AND table_name = ? AND column_name = ?",
		dbName, tableName, columnName).First(&desc)

	if result.Error != nil {
		if result.Error == gorm.ErrRecordNotFound {
			// 创建新记录
			desc = ColumnDescription{
				DatabaseName: dbName,
				TableName:    tableName,
				ColumnName:   columnName,
				Comment:      comment,
			}
			return db.Create(&desc).Error
		}
		return result.Error
	}

	// 更新现有记录
	desc.Comment = comment
	return db.Save(&desc).Error
}

// 获取列注释
func getColumnDescription(dbName, tableName, columnName string) (string, error) {
	if db == nil {
		return "", fmt.Errorf("数据库未连接")
	}

	var desc ColumnDescription
	result := db.Where("database_name = ? AND table_name = ? AND column_name = ?",
		dbName, tableName, columnName).First(&desc)

	if result.Error != nil {
		if result.Error == gorm.ErrRecordNotFound {
			return columnName, nil // 如果没有找到，返回列名作为默认注释
		}
		return "", result.Error
	}

	return desc.Comment, nil
}

// 获取表的所有列注释
func getTableColumnDescriptions(dbName, tableName string) (map[string]string, error) {
	if db == nil {
		return nil, fmt.Errorf("数据库未连接")
	}

	var descriptions []ColumnDescription
	result := db.Where("database_name = ? AND table_name = ?", dbName, tableName).Find(&descriptions)

	if result.Error != nil {
		return nil, result.Error
	}

	descMap := make(map[string]string)
	for _, desc := range descriptions {
		descMap[desc.ColumnName] = desc.Comment
	}

	return descMap, nil
}

// 查询映射表
func searchMapTable(c *gin.Context) {
	if !checkDBConnection(c) {
		return
	}

	dbName := c.DefaultQuery("database", dbConfig.DBName)
	tableName := c.DefaultQuery("table", "jd_map_table")
	sourceColumn := c.DefaultQuery("source_column", "name")
	targetColumn := c.DefaultQuery("target_column", "main_table")
	searchValue := c.DefaultQuery("value", "")

	// 如果是jd_map_table表，验证查询列名，防止SQL注入
	if tableName == "jd_map_table" {
		validColumns := map[string]bool{
			"name":       true,
			"identify":   true,
			"main_table": true,
		}

		if !validColumns[sourceColumn] || !validColumns[targetColumn] {
			c.JSON(http.StatusBadRequest, gin.H{"error": "无效的查询列或目标列"})
			return
		}
	} else {
		// 对于其他表，验证列是否存在
		// 获取表结构
		columns, err := getTableColumns(dbName, tableName)
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": "获取表结构失败: " + err.Error()})
			return
		}

		// 检查列是否存在
		sourceExists := false
		targetExists := false
		for _, col := range columns {
			if col.Name == sourceColumn {
				sourceExists = true
			}
			if col.Name == targetColumn {
				targetExists = true
			}
		}

		if !sourceExists || !targetExists {
			c.JSON(http.StatusBadRequest, gin.H{"error": "指定的列不存在于表中"})
			return
		}
	}

	if searchValue == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "请提供查询值"})
		return
	}

	// 构建查询
	query := fmt.Sprintf("SELECT %s, %s FROM %s.%s WHERE %s LIKE ?",
		sourceColumn, targetColumn, dbName, tableName, sourceColumn)

	// 如果源列和目标列相同，只查询一列
	if sourceColumn == targetColumn {
		query = fmt.Sprintf("SELECT %s FROM %s.%s WHERE %s LIKE ?",
			sourceColumn, dbName, tableName, sourceColumn)
	}

	// 定义动态结果结构
	type Result struct {
		SourceValue string `json:"source_value"`
		TargetValue string `json:"target_value"`
	}

	var results []Result

	// 执行模糊查询
	rows, err := db.Raw(query, "%"+searchValue+"%").Rows()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "查询失败: " + err.Error()})
		return
	}
	defer rows.Close()

	// 处理查询结果
	for rows.Next() {
		if sourceColumn == targetColumn {
			// 如果源列和目标列相同，只有一个值
			var value string
			if err := rows.Scan(&value); err != nil {
				c.JSON(http.StatusInternalServerError, gin.H{"error": "处理结果失败: " + err.Error()})
				return
			}
			results = append(results, Result{
				SourceValue: value,
				TargetValue: value,
			})
		} else {
			// 正常情况，有源值和目标值
			var sourceVal, targetVal string
			if err := rows.Scan(&sourceVal, &targetVal); err != nil {
				c.JSON(http.StatusInternalServerError, gin.H{"error": "处理结果失败: " + err.Error()})
				return
			}
			results = append(results, Result{
				SourceValue: sourceVal,
				TargetValue: targetVal,
			})
		}
	}

	// 检查是否有快捷搜索值
	var quickValues []string
	if tableName == "jd_map_table" && (searchValue == "列名下拉列表" || searchValue == "列值下拉列表" || searchValue == "待查询列" || searchValue == "由查询列值查询所得值") {
		quickValues = []string{"列名下拉列表", "列值下拉列表", "待查询列", "由查询列值查询所得值"}
	}

	// 返回结果
	c.JSON(http.StatusOK, gin.H{
		"data":          results,
		"source_column": sourceColumn,
		"target_column": targetColumn,
		"quick_values":  quickValues,
	})
}

// 获取表的列信息
func getTableColumns(dbName, tableName string) ([]Column, error) {
	if db == nil {
		return nil, fmt.Errorf("数据库未连接")
	}

	// 查询表结构
	query := fmt.Sprintf("SHOW COLUMNS FROM %s.%s", dbName, tableName)
	rows, err := db.Raw(query).Rows()
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var columns []Column
	for rows.Next() {
		var field, fieldType, null, key, defaultValue, extra sql.NullString
		if err := rows.Scan(&field, &fieldType, &null, &key, &defaultValue, &extra); err != nil {
			return nil, err
		}

		// 解析类型和长度
		typeInfo := parseColumnType(fieldType.String)

		// 创建列对象
		col := Column{
			Name: field.String,
			Type: typeInfo.Type,
			Attributes: ColumnAttributes{
				NotNull:       null.String == "NO",
				DefaultValue:  defaultValue.String,
				PrimaryKey:    key.String == "PRI",
				Unique:        key.String == "UNI",
				AutoIncrement: strings.Contains(extra.String, "auto_increment"),
				Length:        typeInfo.Length,
				Scale:         typeInfo.Scale,
				Unsigned:      typeInfo.Unsigned,
			},
		}

		// 获取列注释
		comment, err := getColumnDescription(dbName, tableName, field.String)
		if err == nil && comment != "" {
			col.Comment = comment
		}

		columns = append(columns, col)
	}

	return columns, nil
}

// 解析列类型信息
type TypeInfo struct {
	Type     string
	Length   string
	Scale    string
	Unsigned bool
}

// 解析MySQL列类型
func parseColumnType(typeStr string) TypeInfo {
	info := TypeInfo{}

	// 检查是否为无符号类型
	if strings.Contains(typeStr, "unsigned") {
		info.Unsigned = true
		typeStr = strings.Replace(typeStr, " unsigned", "", 1)
	}

	// 提取类型和长度/精度
	if idx := strings.Index(typeStr, "("); idx > 0 {
		info.Type = strings.ToUpper(typeStr[:idx])

		// 提取括号中的内容
		endIdx := strings.Index(typeStr, ")")
		if endIdx > idx {
			params := typeStr[idx+1 : endIdx]

			// 检查是否有小数位数
			if strings.Contains(params, ",") {
				parts := strings.Split(params, ",")
				info.Length = strings.TrimSpace(parts[0])
				if len(parts) > 1 {
					info.Scale = strings.TrimSpace(parts[1])
				}
			} else {
				info.Length = params
			}
		}
	} else {
		info.Type = strings.ToUpper(typeStr)
	}

	return info
}
